﻿using Microsoft.EntityFrameworkCore;
using Sgr.Domain.Entities.Auditing;
using Sgr.Domain.Repositories;
using Sgr.EntityFrameworkCore;
using Sgr.Exceptions;
using Sgr.Generator;
using Sgr.UPMS.Domain.Tokens;

namespace Sgr.UPMS.Infrastructure.Repositories
{
    /// <summary>
    /// 临时令牌仓储实现
    /// </summary>
    /// <remarks>
    /// 实现临时令牌的数据访问功能：
    /// - 令牌的增删改查
    /// - 令牌编码唯一性检查
    /// - 过期令牌处理
    /// </remarks>
    public class TemporaryTokenRepository<TDbContext>
        : EfCoreRepositoryOfTEntityAndTPrimaryKey<TDbContext, TemporaryToken, long>, ITemporaryTokenRepository where TDbContext : UnitOfWorkDbContext
    {
        private readonly ISegmentNumIdGenerator _numberIdGenerator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContextProvider"></param>
        /// <param name="auditedOperator">审计操作者</param>
        /// <param name="numberIdGenerator">数字ID生成器</param>
        /// <exception cref="BusinessException">参数为空时抛出异常</exception>
        public TemporaryTokenRepository(
            IDbContextProvider<TDbContext> dbContextProvider,
            IAuditedOperator auditedOperator,
            ISegmentNumIdGenerator numberIdGenerator)
            : base(dbContextProvider, auditedOperator)
        {
            _numberIdGenerator = numberIdGenerator ?? throw new ArgumentNullException(nameof(numberIdGenerator));
        }

        /// <summary>
        /// 检查并设置主键Id
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        protected override async Task CheckAndSetIdAsync(TemporaryToken entity, CancellationToken cancellationToken = default)
        {
            if (entity.Id == 0)
                entity.Id = await _numberIdGenerator.GetUniqueIdAsync(UpmsConstant.DEFAULT_SEGMENT_KEY, cancellationToken);
        }

        /// <summary>
        /// 是否存在指定编码的令牌
        /// </summary>
        /// <param name="code">令牌编码</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> ExistsCodeAsync(string code, CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrEmpty(code, nameof(code));

            var dbContext = await GetDbContextAsync(cancellationToken);
            return await dbContext.Set<TemporaryToken>()
                .AsNoTracking()
                .Where(x => x.Code == code)
                .AnyAsync(cancellationToken);
        }

        /// <summary>
        /// 根据编码获取临时令牌
        /// </summary>
        /// <param name="code">令牌编码</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<TemporaryToken?> GetByCodeAsync(string code, CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrEmpty(code, nameof(code));

            var dbContext = await GetDbContextAsync(cancellationToken);
            return await dbContext.Set<TemporaryToken>()
                .AsNoTracking()
                .FirstOrDefaultAsync(x => x.Code == code, cancellationToken);
        }
    }
}